﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Collections.Generic;
using Card.Security;

namespace Card.Web.ImageService
{
    public class UpLoadImageHelper
    {
        private static List<string> m_AllowImageTypes = new List<string>() { "gif", "jpg", "jpeg", "png", "bmp" };
        /// <summary>
        /// 允许上传图片类型
        /// </summary>
        public static List<string> AllowImageTypes
        {
            get
            {
                return m_AllowImageTypes;
            }
        }

        private static bool EnableSecurity
        {
            get
            {
                if (ConfigurationManager.AppSettings["EnableSecurity"] != null)
                {
                    return string.Compare(ConfigurationManager.AppSettings["EnableSecurity"], "Y", true) == 0;
                }
                return false;
            }
        }

        /// <summary>
        /// 保存上传图片
        /// </summary>
        /// <param name="context"></param>
        public static void SaveImage(HttpContext context)
        {
            string isSuccess = CONST.YES_NO.YES;
            string strMessage = string.Empty;
            string responseResult = string.Format("{{'result':'{0}','fileName':'','message':''}}", CONST.YES_NO.NO.ToLower());
            string fileName = string.Empty; //返回的上传后的文件名
            try
            {
                string originalImgName = context.Request.QueryString["fileName"];
                string type = context.Request.QueryString["t"].ToUpper();

                string suffix = originalImgName.Substring(originalImgName.LastIndexOf('.')).ToLower().TrimStart('.');


                if (UpLoadImageHelper.AllowImageTypes.Contains(suffix))
                {
                    if (string.Compare(type, CONST.UPLOAD_IMAGE_TYPE.TEMPLATE_IMAGE, true) == 0)
                    {
                        if (!EnableSecurity || BAF.Security.CookieManager.GetPassport().IsLogin)
                        {
                            fileName = SaveTemplateImage(context, suffix, ref isSuccess, ref strMessage);
                        }
                        else
                        {
                            isSuccess = CONST.YES_NO.NO;
                            strMessage = "只有管理员才能上传名片模板！";
                        }

                        responseResult = string.Format("{{'result':'{0}','fileName':'{1}','message':'{2}'}}", isSuccess.ToLower(), fileName, Card.Utility.TextUtility.JSEscape(strMessage));
                    }
                    else if (string.Compare(type, CONST.UPLOAD_IMAGE_TYPE.LOGO, true) == 0)
                    {
                        int logoID = 0;
                        if (!EnableSecurity || BAF.Security.CookieManager.GetPassport().IsLogin)
                        {
                            fileName = SaveLogoImage(context, suffix, ref  isSuccess, ref  strMessage, ref  logoID);
                        }
                        else
                        {
                            isSuccess = CONST.YES_NO.NO;
                            strMessage = "只有管理员才能上传LOGO！";
                        }
                        responseResult = string.Format("{{'result':'{0}','fileName':'{1}','logoID':'{2}','message':'{3}'}}", isSuccess.ToLower(), fileName, logoID, Card.Utility.TextUtility.JSEscape(strMessage));
                    }
                    else if (string.Compare(type, CONST.UPLOAD_IMAGE_TYPE.USER_LOGO, true) == 0)
                    {
                        Entity.UserLogo ulogo = null;
                        if (Card.Security.CookieManager.GetPassport().IsLogin)
                        {
                            ulogo = SaveUserLogoImage(context, originalImgName, suffix, ref  isSuccess, ref  strMessage);
                            responseResult = string.Format("{{'result':'{0}','fileName':'{1}','w':'{2}','h':'{3}','message':'{4}'}}", isSuccess.ToLower(), ulogo.Image, ulogo.Width, ulogo.Height, Card.Utility.TextUtility.JSEscape(strMessage));
                        }
                        else
                        {
                            isSuccess = CONST.YES_NO.NO;
                            responseResult = "{'result':'n','message':'登录后才能上传LOGO！'}";
                        }
                    }
                    else if (string.Compare(type, CONST.UPLOAD_IMAGE_TYPE.SITE_SETTING, true) == 0)
                    {
                        if (Card.Security.CookieManager.GetPassport().IsLogin)
                        {
                            fileName = SaveSiteSettingImage(context,suffix, ref  isSuccess, ref  strMessage);
                            responseResult = string.Format("{{'result':'{0}','fileName':'{1}','message':'{2}'}}", isSuccess.ToLower(), fileName, Card.Utility.TextUtility.JSEscape(strMessage));
                        }
                        else
                        {
                            isSuccess = CONST.YES_NO.NO;
                            responseResult = "{'result':'n','message':'你没有权限执行该操作！'}";
                        }
                    }
                }
                else
                {
                    strMessage = string.Format("文件格式错误！允许的格式：{0}", string.Join(",", UpLoadImageHelper.AllowImageTypes.ToArray()));
                    isSuccess = CONST.YES_NO.NO;
                    responseResult = string.Format("{{'result':'{0}','fileName':'{1}','message':'{2}'}}", isSuccess.ToLower(), fileName, Card.Utility.TextUtility.JSEscape(strMessage));
                }
            }
            catch (Exception ex)
            {
                Card.Log.Logger.Error(ex.ToString());
                strMessage = string.Format("{0}", ex.Message);
                responseResult = string.Format("{{'result':'{0}','fileName':'{1}','message':'{2}'}}", CONST.YES_NO.NO.ToLower(), fileName, Card.Utility.TextUtility.JSEscape(strMessage));
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write(responseResult);
            context.Response.Flush();
            context.Response.End();
        }

        /// <summary>
        /// 保存模板图片
        /// </summary>
        /// <param name="context"></param>
        /// <param name="isSuccess"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        private static string SaveTemplateImage(HttpContext context, string suffix, ref string isSuccess, ref string strMessage)
        {
            BAF.Security.Passport passport = BAF.Security.CookieManager.GetPassport();
            string imageType = context.Request.QueryString["it"].ToUpper();
            int templateID = 0;
            if (int.TryParse(context.Request.QueryString["id"], out templateID)
                && (string.Compare(imageType, CONST.CARD_FACE_TYPE.BACK) == 0 || string.Compare(imageType, CONST.CARD_FACE_TYPE.FRONT) == 0))
            {
                Entity.Template template = BLL.TemplateManager.GetEntity(templateID, null);
                if (template != null)
                {
                    string prefix = string.Format("{0}{1}99{2}", DateTime.Now.ToString("yyyyMMddHHmmss"), imageType, templateID);
                    if (string.Compare(imageType, CONST.CARD_FACE_TYPE.BACK) == 0)
                    {
                        template.BackImage = string.Format("{0}.{1}", prefix, suffix);
                    }
                    else
                    {
                        template.FrontImage = string.Format("{0}.{1}", prefix, suffix);
                    }

                    byte[] buffer = new byte[context.Request.ContentLength];
                    context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);

                    string folder = context.Server.MapPath(string.Format("TemplateImages/{0}/{1}/", prefix.Substring(0, 4), prefix.Substring(4, 2)));

                    if (!Directory.Exists(folder))
                    {
                        Directory.CreateDirectory(folder);
                    }

                    MemoryStream m = new MemoryStream(buffer);
                    Image img = Image.FromStream(m);
                    if (img.Width < img.Height)
                    {
                        Helper.ImageHelper.ToThumbnail(img, folder + string.Format("{0}T.{1}", prefix, suffix), suffix, 240, 400, true);
                    }
                    else
                    {
                        Helper.ImageHelper.ToThumbnail(img, folder + string.Format("{0}T.{1}", prefix, suffix), suffix, 400, 240, true);
                    }
                    
                    img.Save(folder + (string.Compare(imageType, CONST.CARD_FACE_TYPE.BACK) == 0 ? template.BackImage : template.FrontImage));
                    img.Dispose();
                    m.Close();

                    isSuccess = BLL.TemplateManager.Update(template, null) ? CONST.YES_NO.YES : CONST.YES_NO.NO;

                    return template.BackImage;
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 保存LOGO图片
        /// </summary>
        /// <param name="context"></param>
        /// <param name="suffix"></param>
        /// <param name="isSuccess"></param>
        /// <param name="strMessage"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private static string SaveLogoImage(HttpContext context, string suffix, ref string isSuccess, ref string strMessage, ref int id)
        {
            int.TryParse(context.Request.QueryString["id"], out id);
            string logoName = string.IsNullOrEmpty(context.Request.QueryString["n"]) ? string.Empty : Card.Utility.TextUtility.JSUnescape(context.Request.QueryString["n"]);
            string logoType = string.IsNullOrEmpty(context.Request.QueryString["lt"]) ? string.Empty : context.Request.QueryString["lt"].Trim().ToUpper();
            Entity.Logo logo = (id <= 0) ? new Entity.Logo() { ID = BAF.BLL.SYSSequenceManager.GetSequence(CONST.SEQUENCE_CODE.LOGO_ID, null) } : BLL.LogoManager.GetEntity(id, null);
            logo = logo == null ? new Entity.Logo() { ID = BAF.BLL.SYSSequenceManager.GetSequence(CONST.SEQUENCE_CODE.LOGO_ID, null) } : logo;
            id = logo.ID;
            logo.Name = logoName;
            logo.TypeCode = logoType;
            logo.Image = string.Format("{0}9999{1}.{2}", DateTime.Now.ToString("yyyyMMddHHmmss"), logo.ID, suffix);

            byte[] buffer = new byte[context.Request.ContentLength];
            context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);

            string folder = context.Server.MapPath("logoImages/");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            MemoryStream m = new MemoryStream(buffer);
            Image img = Image.FromStream(m);
            img.Save(folder + logo.Image);

            logo.Width = img.Width;
            logo.Height = img.Height;

            img.Dispose();
            m.Close();

            isSuccess = BLL.LogoManager.Save(logo, null) ? CONST.YES_NO.YES : CONST.YES_NO.NO;

            return logo.Image;
        }
        /// <summary>
        /// 保存用户logo
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fileName"></param>
        /// <param name="suffix"></param>
        /// <param name="isSuccess"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        private static Entity.UserLogo SaveUserLogoImage(HttpContext context, string fileName, string suffix, ref string isSuccess, ref string strMessage)
        {
            Card.Security.Passport passport = Card.Security.CookieManager.GetPassport();
            Entity.UserLogo ulogo = new Card.Entity.UserLogo();
            ulogo.Name = fileName;
            ulogo.UserID = passport.UserID;
            ulogo.Image = string.Format("{0}-{1}.{2}", passport.UserID, DateTime.Now.ToString("yyyyMMddHHmmss"), suffix);

            byte[] buffer = new byte[context.Request.ContentLength];
            context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);

            string folder = context.Server.MapPath("logoImages/");
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            MemoryStream m = new MemoryStream(buffer);
            Image img = Image.FromStream(m);
            img.Save(folder + ulogo.Image);

            ulogo.Width = img.Width;
            ulogo.Height = img.Height;

            img.Dispose();
            m.Close();
            isSuccess = BLL.UserLogoManager.Save(ulogo, null) ? CONST.YES_NO.YES : CONST.YES_NO.NO;

            return ulogo;
        }
        /// <summary>
        /// 保存站点设定图片
        /// </summary>
        /// <param name="context"></param>
        /// <param name="suffix"></param>
        /// <param name="isSuccess"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        private static string SaveSiteSettingImage(HttpContext context, string suffix, ref string isSuccess, ref string strMessage)
        {
            try
            {
                byte[] buffer = new byte[context.Request.ContentLength];
                context.Request.InputStream.Read(buffer, 0, context.Request.ContentLength);

                string folder = context.Server.MapPath("site-images/");
                string fileName = string.Format("{0}.{1}", Guid.NewGuid().ToString(), suffix);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                MemoryStream m = new MemoryStream(buffer);
                Image img = Image.FromStream(m);
                img.Save(folder + fileName);
                img.Dispose();
                m.Close();

                isSuccess = CONST.YES_NO.YES;
                return fileName;
            }
            catch (Exception ex)
            {
                isSuccess = CONST.YES_NO.NO;
                strMessage = ex.Message;
                Card.Log.Logger.Error(ex.ToString());
            }
            return string.Empty;
        }
    }
}
